import { ApiService } from './ApiService'
import { StorageUtil } from '../utils/StorageUtil'
import { Constants } from '../utils/Constants'

/**
 * 餐厅服务类
 */
export class RestaurantService {
  private static instance: RestaurantService
  private apiService: ApiService
  private storageUtil: StorageUtil

  private constructor() {
    this.apiService = ApiService.getInstance()
    this.storageUtil = StorageUtil.getInstance()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): RestaurantService {
    if (!this.instance) {
      this.instance = new RestaurantService()
    }
    return this.instance
  }

  /**
   * 获取餐厅列表
   */
  async getRestaurants(params?: {
    category?: string
    search?: string
    sortBy?: string
    page?: number
    pageSize?: number
  }): Promise<any> {
    try {
      return await this.apiService.getRestaurants(params)
    } catch (error) {
      console.error('获取餐厅列表失败:', error)
      throw error
    }
  }

  /**
   * 获取餐厅详情
   */
  async getRestaurantDetail(restaurantId: string): Promise<any> {
    try {
      return await this.apiService.getRestaurantDetail(restaurantId)
    } catch (error) {
      console.error('获取餐厅详情失败:', error)
      throw error
    }
  }

  /**
   * 获取餐厅菜品
   */
  async getRestaurantMenu(restaurantId: string, category?: string): Promise<any> {
    try {
      const params = { restaurantId }
      if (category) {
        params['category'] = category
      }
      return await this.apiService.getMenuItems(params)
    } catch (error) {
      console.error('获取餐厅菜品失败:', error)
      throw error
    }
  }

  /**
   * 获取菜品详情
   */
  async getMenuItemDetail(itemId: string): Promise<any> {
    try {
      return await this.apiService.getMenuItemDetail(itemId)
    } catch (error) {
      console.error('获取菜品详情失败:', error)
      throw error
    }
  }

  /**
   * 获取菜品分类
   */
  async getMenuCategories(restaurantId: string): Promise<any> {
    try {
      return await this.apiService.getMenuCategories(restaurantId)
    } catch (error) {
      console.error('获取菜品分类失败:', error)
      throw error
    }
  }

  /**
   * 搜索餐厅
   */
  async searchRestaurants(searchTerm: string): Promise<any> {
    try {
      return await this.apiService.searchRestaurants(searchTerm)
    } catch (error) {
      console.error('搜索餐厅失败:', error)
      throw error
    }
  }

  /**
   * 获取热门餐厅
   */
  async getPopularRestaurants(limit: number = 10): Promise<any> {
    try {
      return await this.apiService.getPopularRestaurants(limit)
    } catch (error) {
      console.error('获取热门餐厅失败:', error)
      throw error
    }
  }

  /**
   * 获取附近餐厅
   */
  async getNearbyRestaurants(latitude: number, longitude: number, radius: number = 5000): Promise<any> {
    try {
      return await this.apiService.getNearbyRestaurants({
        latitude,
        longitude,
        radius
      })
    } catch (error) {
      console.error('获取附近餐厅失败:', error)
      throw error
    }
  }

  /**
   * 获取餐厅评价
   */
  async getRestaurantReviews(restaurantId: string, page: number = 1, pageSize: number = 10): Promise<any> {
    try {
      return await this.apiService.getRestaurantReviews(restaurantId, page, pageSize)
    } catch (error) {
      console.error('获取餐厅评价失败:', error)
      throw error
    }
  }

  /**
   * 添加餐厅评价
   */
  async addRestaurantReview(restaurantId: string, reviewData: {
    rating: number
    comment: string
    images?: string[]
  }): Promise<any> {
    try {
      const currentUser = await this.storageUtil.getUserInfo()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.addRestaurantReview(restaurantId, {
        userId: currentUser.id,
        ...reviewData
      })
    } catch (error) {
      console.error('添加餐厅评价失败:', error)
      throw error
    }
  }

  /**
   * 收藏餐厅
   */
  async favoriteRestaurant(restaurantId: string): Promise<any> {
    try {
      const currentUser = await this.storageUtil.getUserInfo()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.favoriteRestaurant(restaurantId, currentUser.id)
    } catch (error) {
      console.error('收藏餐厅失败:', error)
      throw error
    }
  }

  /**
   * 取消收藏餐厅
   */
  async unfavoriteRestaurant(restaurantId: string): Promise<any> {
    try {
      const currentUser = await this.storageUtil.getUserInfo()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.unfavoriteRestaurant(restaurantId, currentUser.id)
    } catch (error) {
      console.error('取消收藏餐厅失败:', error)
      throw error
    }
  }

  /**
   * 获取收藏的餐厅
   */
  async getFavoriteRestaurants(): Promise<any> {
    try {
      const currentUser = await this.storageUtil.getUserInfo()
      if (!currentUser) {
        throw new Error('用户未登录')
      }

      return await this.apiService.getFavoriteRestaurants(currentUser.id)
    } catch (error) {
      console.error('获取收藏的餐厅失败:', error)
      throw error
    }
  }

  /**
   * 检查餐厅是否已收藏
   */
  async isRestaurantFavorited(restaurantId: string): Promise<boolean> {
    try {
      const currentUser = await this.storageUtil.getUserInfo()
      if (!currentUser) {
        return false
      }

      const favorites = await this.getFavoriteRestaurants()
      return favorites.some(fav => fav.id === restaurantId)
    } catch (error) {
      console.error('检查餐厅收藏状态失败:', error)
      return false
    }
  }

  /**
   * 获取餐厅营业时间状态
   */
  getRestaurantStatus(restaurant: any): string {
    if (!restaurant.businessHours) {
      return '未知'
    }

    const now = new Date()
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()
    const currentTime = currentHour * 60 + currentMinute

    const [openTime, closeTime] = restaurant.businessHours.split('-')
    const [openHour, openMinute] = openTime.split(':').map(Number)
    const [closeHour, closeMinute] = closeTime.split(':').map(Number)
    
    const openMinutes = openHour * 60 + openMinute
    const closeMinutes = closeHour * 60 + closeMinute

    if (currentTime >= openMinutes && currentTime <= closeMinutes) {
      return '营业中'
    } else {
      return '已打烊'
    }
  }

  /**
   * 计算配送费
   */
  calculateDeliveryFee(distance: number): number {
    if (distance <= 1000) {
      return Constants.DELIVERY_FEE
    } else if (distance <= 3000) {
      return Constants.DELIVERY_FEE + 2
    } else {
      return Constants.DELIVERY_FEE + 5
    }
  }

  /**
   * 格式化距离
   */
  formatDistance(distance: number): string {
    if (distance < 1000) {
      return `${distance}m`
    } else {
      return `${(distance / 1000).toFixed(1)}km`
    }
  }

  /**
   * 格式化营业时间
   */
  formatBusinessHours(businessHours: string): string {
    return businessHours.replace('-', ' - ')
  }

  /**
   * 获取餐厅评分星级
   */
  getRatingStars(rating: number): string {
    const fullStars = Math.floor(rating)
    const hasHalfStar = rating % 1 >= 0.5
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0)
    
    let stars = ''
    for (let i = 0; i < fullStars; i++) {
      stars += '★'
    }
    if (hasHalfStar) {
      stars += '☆'
    }
    for (let i = 0; i < emptyStars; i++) {
      stars += '☆'
    }
    
    return stars
  }
}